/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.LearnProgress;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.service.Base64ImageService;
import com.lczyfz.istep.common.service.FileUploadService;
import com.lczyfz.istep.common.utils.*;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.ResourceCourseware;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import com.lczyfz.istep.modules.resource.service.ResourceCourseService;
import com.lczyfz.istep.modules.resource.service.ResourceCoursewareService;
import com.lczyfz.istep.modules.resource.service.ResourceFileService;
import com.lczyfz.istep.modules.scene.entity.SceneEnvironment;
import com.lczyfz.istep.modules.scene.service.SceneEnvironmentService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.teach.service.TeachStudentService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 课件管理Controller
 * @author dh
 * @version 2017-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourceCourseware")
public class ResourceCoursewareController extends BaseController {

	@Autowired
	private ResourceCoursewareService resourceCoursewareService;
	@Autowired
	private ResourceCourseService resourceCourseService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private FileUploadService fileUploadService;
	@Autowired
	private SceneEnvironmentService sceneEnvironmentService;
	@Autowired
	private ResourceFileService resourceFileService;
	@Autowired
	private TeachStudentService teachStudentService;
	private static String fileid;
	@Autowired
	private Base64ImageService base64ImageService1;
	@ModelAttribute
	public ResourceCourseware get(@RequestParam(required=false) String id) {
		ResourceCourseware entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceCoursewareService.get(id);
		}
		if (entity == null){
			entity = new ResourceCourseware();
		}
		return entity;
	}

	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourceCourseware resourceCourseware, HttpServletRequest request, HttpServletResponse response, Model model) {

		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");

		}
		else
		{
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourceCourseware> page = resourceCoursewareService.findPage(new Page<ResourceCourseware>(request, response), resourceCourseware);
		model.addAttribute("page", page);
		return "modules/resource/resourceCoursewareList";
	}
	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = "findPageByCourseId")
	public String findPageByCourseId(ResourceCourseware resourceCourseware, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("courseId=== [{}]", resourceCourseware.getCourseId());
		Page<ResourceCourseware> page = resourceCoursewareService.findPageByCourseId(new Page<ResourceCourseware>(request, response), resourceCourseware);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		model.addAttribute("page", page);
		return "modules/resource/resourceCoursewareList";
	}
	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = "form")
	public String form(ResourceCourseware resourceCourseware, Model model,@RequestParam(required = false)String type,String detail) {
//		logger.debug("查看详情type=：[{}]", type);
//		if(detail!=null&&detail.equals("detail"))
//		{
//			resourceCourseware=get(resourceCourseware.getId());
//		}else {
//			model.addAttribute("type", type);
//		}

		if(resourceCourseware!=null&&resourceCourseware.getId()!=null&&!resourceCourseware.getId().equals(""))
		{
			ResourceFile temp=new ResourceFile();
			temp.setResourceId(resourceCourseware.getId());
			temp.setType(ResourceConstants.videoMateria);
			List<ResourceFile> videoMaterials= resourceFileService.findList(temp);

			temp.setType(ResourceConstants.documentMateria);
			List<ResourceFile> documentMaterials= resourceFileService.findList(temp);

			temp.setType(ResourceConstants.coursewareDocument);
			List<ResourceFile> coursewareDocuments= resourceFileService.findList(temp);

			String videoFileIds="";
			String fileIds="";
			String coursewareDocumentIds="";
			String videoMaterial="";
			String coursewareDocument="";
			if(coursewareDocuments.size()>0) {
				coursewareDocumentIds = coursewareDocuments.get(0).getId();
				coursewareDocument=coursewareDocuments.get(0).getName();
			}
			for(int i=0;i<videoMaterials.size();i++)
			{
				if(i==0)
					videoFileIds=videoMaterials.get(i).getId();
				else
					videoFileIds=videoFileIds+","+videoMaterials.get(i).getId();
			}
			for(int i=0;i<documentMaterials.size();i++)
			{
				if(i==0)
					fileIds=documentMaterials.get(i).getId();
				else
					fileIds=fileIds+","+documentMaterials.get(i).getId();
			}


			model.addAttribute("videoFileIds", videoFileIds);
			model.addAttribute("fileIds", fileIds);
			model.addAttribute("videoMaterials", videoMaterials);
			model.addAttribute("documentMaterials", documentMaterials);
			model.addAttribute("coursewareDocumentIds", coursewareDocumentIds);
			model.addAttribute("coursewareDocumentURL", coursewareDocument);
			logger.debug("videoMaterials=== [{}]== [{}]", videoMaterials.size(), videoFileIds);
			logger.debug("documentMaterials=== [{}]== [{}]", documentMaterials.size(),fileIds);
			logger.debug("coursewareDocumentIds=== [{}]== [{}]", coursewareDocuments.size(),coursewareDocumentIds);

			ResourceFile resourceFile =new ResourceFile();
			resourceFile.setResourceId(resourceCourseware.getId());
			resourceFile.setType(ResourceConstants.videoMateria);
			List<ResourceFile> ls= resourceFileService.findList(resourceFile);

			if(ls.size()>0)
			{
				videoMaterial=ls.get(0).getName();
				logger.debug("videoMaterial=== [{}]", videoMaterial);

			}
			model.addAttribute("videoMaterialURL", videoMaterial);

		}



		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}else
			model.addAttribute("isSuperAdmin", "false");
		logger.debug("CoursewareAttribute===11111 [{}]",resourceCourseware.getCoursewareAttribute());

		//查询教学实验环境列表
		SceneEnvironment sceneEnvironment=new SceneEnvironment();
		List<SceneEnvironment> sceneEnvironmentList=sceneEnvironmentService.findList(sceneEnvironment);
		logger.debug("sceneEnvironmentList===：[{}]",sceneEnvironmentList.size());


		model.addAttribute("sceneEnvironmentList", sceneEnvironmentList);
		model.addAttribute("resourceCourseware", resourceCourseware);
		return "modules/resource/resourceCoursewareForm";
	}

	/**
	 * 查看课件详情
	 * @param resourceCourseware
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("resource:resourceCourse:view")
	@RequestMapping(value = "detail")
	public String detail(ResourceCourseware resourceCourseware, Model model, HttpServletRequest request, HttpServletResponse response) {

		logger.debug("resourceCoursewareId=== [{}]", resourceCourseware.getId());
		ResourceFile resourceFile =new ResourceFile();
		resourceFile.setResourceId(resourceCourseware.getId());
		resourceFile.setType(ResourceConstants.documentMateria);
		Page<ResourceFile> page = resourceFileService.findPage(new Page<ResourceFile>(request, response), resourceFile);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		resourceFile.setType(ResourceConstants.videoMateria);
		List<ResourceFile> ls= resourceFileService.findList(resourceFile);
		String videoMaterial="";
		String coursewareDocumentURL="";
		if(ls.size()>0)
		{
			videoMaterial=ls.get(0).getName();
			logger.debug("videoMaterial=== [{}]", videoMaterial);

		}
		if(resourceCourseware.getEnvironmentId()!=null&&!resourceCourseware.getEnvironmentId().equals(""))
			resourceCourseware.setEnvironmentId(sceneEnvironmentService.get(resourceCourseware.getEnvironmentId()).getEnvironmentName());


		resourceFile.setType(ResourceConstants.coursewareDocument);
		List<ResourceFile> coursewareDocuments= resourceFileService.findList(resourceFile);
		logger.debug("coursewareDocuments.size=== [{}]", coursewareDocuments.size());

		if(coursewareDocuments.size()>0)
		{
			coursewareDocumentURL=coursewareDocuments.get(0).getName();
			logger.debug("coursewareDocumentURL=== [{}]", coursewareDocumentURL);

		}
		model.addAttribute("coursewareDocumentURL", coursewareDocumentURL);
		model.addAttribute("videoMaterialURL", videoMaterial);
		model.addAttribute("page", page);
		model.addAttribute("resourceCourseware", resourceCourseware);
		return "modules/resource/resourceCoursewareDetail";
	}
	@RequiresPermissions("resource:resourceCourseware:edit")
	@RequestMapping(value = "save")
	public String save(ResourceCourseware resourceCourseware, Model model, RedirectAttributes redirectAttributes,String videoFileIds,String fileIds,String coursewareDocumentIds) {
		if (!beanValidator(model, resourceCourseware)){
			return form(resourceCourseware, model,null,null);
		}
		logger.debug("dingh===111="+resourceCourseware.getId());
		logger.debug("dingh===document=1=" + resourceCourseware.getDocument());

		if(resourceCourseware.getDocument()!=null)
		{
			resourceCourseware.setDocument(FormatHtmlUtil.formatHtml(StringEscapeUtils.unescapeHtml4(resourceCourseware.getDocument())));
			logger.debug("dingh===document=2=" + resourceCourseware.getDocument());

		}
		logger.debug("插入课件===！"+resourceCourseware.getCoursewareAttribute());
		int message=0;
		ResourceCourseware rc=new ResourceCourseware();
		rc.setCoursewareName(resourceCourseware.getCoursewareName());
		List<ResourceCourseware> temp = resourceCoursewareService.findList(rc);
		if (resourceCoursewareService.get(resourceCourseware) == null) {
			logger.debug("新增===");
			if (temp != null && temp.size() > 0 && temp.get(0).getCoursewareName().equals(resourceCourseware.getCoursewareName())) {
				message=1;
			} else {
				resourceCoursewareService.save(resourceCourseware);
				if(coursewareDocumentIds!=null&&!coursewareDocumentIds.equals(""))
				{

						logger.debug("coursewareDocumentIds：[{}]",coursewareDocumentIds);
						ResourceFile resourceFile = resourceFileService.get(coursewareDocumentIds);
						resourceFile.setResourceId(resourceCourseware.getId());
						resourceFileService.update(resourceFile);

					    //更新图片的resource_id
						ResourceFile resourceFile2 = new ResourceFile();
						resourceFile2.setResourceId(resourceFile.getId());
						List<ResourceFile> imgList = resourceFileService.findList(resourceFile2);
						for (ResourceFile anImgList : imgList) {
							anImgList.setResourceId(resourceFile.getResourceId());
							resourceFileService.update(anImgList);

						}
						logger.debug("CoursewareId：[{}]", resourceFile.getResourceId());

				}
				if(videoFileIds!=null&&!videoFileIds.equals(""))
				{
					String [] videoList=videoFileIds.split(",");
					for(int i=0;i<videoList.length;i++)
					{
						logger.debug("videoFileId：[{}]", videoList[i]);
						ResourceFile resourceFile = resourceFileService.get(videoList[i]);
						resourceFile.setResourceId(resourceCourseware.getId());
						resourceFileService.update(resourceFile);
						logger.debug("CoursewareId：[{}]", resourceFile.getResourceId());

					}
				}
				if(fileIds!=null&&!fileIds.equals(""))
				{
					String [] documentList=fileIds.split(",");
					for(int i=0;i<documentList.length;i++)
					{
						ResourceFile resourceFile = resourceFileService.get(documentList[i]);
						resourceFile.setResourceId(resourceCourseware.getId());
						resourceFileService.update(resourceFile);

					}
				}
				message=2;
			}
		}else{
			logger.debug("修改===");
			resourceCoursewareService.save(resourceCourseware);

			ResourceFile temp1=new ResourceFile();
			temp1.setResourceId(resourceCourseware.getId());
//			temp1.setType(ResourceConstants.videoMateria);
//			List<ResourceFile> videoMaterials= resourceFileService.findList(temp);
//
//			temp1.setType(ResourceConstants.documentMateria);
//			List<ResourceFile> documentMaterials= resourceFileService.findList(temp);




			if(videoFileIds!=null&&!videoFileIds.equals(""))
			{
				logger.debug("dingh===videoFileIds==="+videoFileIds);

				String [] videoList=videoFileIds.split(",");
				ResourceFile temp2=new ResourceFile();
				temp2.setResourceId(resourceCourseware.getId());
				temp2.setType(ResourceConstants.videoMateria);
				List<ResourceFile> list= resourceFileService.findList(temp2);
				for(int i=0;i<list.size();i++)
				{
					if(!list.get(i).getId().equals(videoFileIds)) {
						resourceFileService.delete(list.get(i));
						File file=new File(list.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("dingh===删除文件：[{}]", list.get(i).getLocalUrl());
						}
					}
				}



					ResourceFile resourceFile = resourceFileService.get(videoFileIds);
					resourceFile.setResourceId(resourceCourseware.getId());
					resourceFileService.update(resourceFile);
					logger.debug("CoursewareId：[{}]", resourceFile.getResourceId());

			}
			if(coursewareDocumentIds!=null&&!coursewareDocumentIds.equals(""))
			{
				temp1.setType(ResourceConstants.coursewareDocument);
				List<ResourceFile> coursewareDocuments= resourceFileService.findList(temp1);
				for(int i=0;i<coursewareDocuments.size();i++)
				{
					if(!coursewareDocuments.get(i).getId().equals(coursewareDocumentIds)) {
						resourceFileService.delete(coursewareDocuments.get(i));
						File file=new File(coursewareDocuments.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("删除文件：[{}]", coursewareDocuments.get(i).getLocalUrl());
						}
						temp1.setType(ResourceConstants.image);
						temp1.setResourceId(coursewareDocuments.get(i).getId());
						List<ResourceFile> pdfFiles= resourceFileService.findList(temp1);
						for(int j=0;j<pdfFiles.size();j++)
						{
							file=new File(pdfFiles.get(j).getLocalUrl());
							if(file.exists()) {
								file.delete();
								logger.debug("删除pdf：[{}]", coursewareDocuments.get(i).getLocalUrl());
							}
						}

					}


				}
				logger.debug("coursewareDocumentIds===11==：[{}]",coursewareDocumentIds);

				logger.debug("coursewareDocumentIds：[{}]",coursewareDocumentIds);
				ResourceFile resourceFile = resourceFileService.get(coursewareDocumentIds);
				resourceFile.setResourceId(resourceCourseware.getId());
				resourceFileService.update(resourceFile);
				logger.debug("CoursewareId：[{}]", resourceFile.getResourceId());


				//修改时，先删除之前的图片
				ResourceFile resourceFile3 = new ResourceFile();
				resourceFile3.setResourceId(resourceCourseware.getId());
				resourceFile3.setType(ResourceConstants.image);
				List<ResourceFile> deleteImgList = resourceFileService.findList(resourceFile3);
				for (ResourceFile anDeleteImgList : deleteImgList) {
					resourceFileService.delete(anDeleteImgList);
				}

				//更新图片的resource_id
				ResourceFile resourceFile2 = new ResourceFile();
				resourceFile2.setResourceId(resourceFile.getId());
				List<ResourceFile> imgList = resourceFileService.findList(resourceFile2);
				for (ResourceFile anImgList : imgList) {
					anImgList.setResourceId(resourceFile.getResourceId());
					resourceFileService.update(anImgList);
				}

			}
			if(fileIds!=null&&!fileIds.equals(""))
			{
				String [] documentList=fileIds.split(",");
				logger.debug("dingh====删除文件=documentList：[{}]", documentList);

				temp1.setType(ResourceConstants.documentMateria);
				List<ResourceFile> list= resourceFileService.findList(temp1);
				logger.debug("dingh====删除文件=size：[{}]", list.size());

				for(int i=0;i<list.size();i++)
				{
					boolean delete=true;
					for(int j=0;j<documentList.length;j++)
					{
						if(list.get(i).getId().equals(documentList[j]))
						{
							delete=false;
							break;
						}
					}
					logger.debug("dingh====删除文件=delete：[{}]", delete);

					if(delete) {
						resourceFileService.delete(list.get(i));
						File file=new File(list.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("dingh====删除文件：[{}]", list.get(i).getLocalUrl());
						}
					}
				}

				for(int i=0;i<documentList.length;i++)
				{
					ResourceFile resourceFile = resourceFileService.get(documentList[i]);
					resourceFile.setResourceId(resourceCourseware.getId());
					resourceFileService.update(resourceFile);

				}
			}
			message=3;
		}
		switch (message)
		{
			case 1:
				addMessage(redirectAttributes, "新增课件'" + resourceCourseware.getCoursewareName() + "'失败，该课件已存在");
				break;
			case 2:
				addMessage(redirectAttributes, "新增课件 '" + resourceCourseware.getCoursewareName() + "'成功");
				break;
			case 3:
				addMessage(redirectAttributes, "修改课件 '" + resourceCourseware.getCoursewareName() + "'成功");
				break;
			default:
				logger.debug("message：[{}]", message);
		}
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCourseware/?repage";
	}
	@RequiresPermissions("resource:resourceCourseware:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourceCourseware resourceCourseware, RedirectAttributes redirectAttributes) {
		ResourceFile material=new ResourceFile();
		material.setResourceId(resourceCourseware.getId());
		//删除素材表数据和ftp文件
		List<ResourceFile> materialList = resourceFileService.getMaterialsByCoursewareId(material);
		for(int i=0;i<materialList.size();i++)
		{
			resourceFileService.delete(materialList.get(i));  //数据库文件记录删除
			if(materialList.get(i).getLocalUrl()!=null&&!materialList.get(i).getLocalUrl().equals("")) {
				File file=new File(materialList.get(i).getLocalUrl());
				if(file.exists()) {
					file.delete();
					logger.debug("删除文件：[{}]", materialList.get(i).getLocalUrl());
				}
			}
			material.setType(ResourceConstants.image);
			material.setResourceId(materialList.get(i).getId());
			List<ResourceFile> pdfFiles= resourceFileService.findList(material);
			for(int j=0;j<pdfFiles.size();j++)
			{
				File file=new File(pdfFiles.get(j).getLocalUrl());
				if(file.exists()) {
					file.delete();
					logger.debug("删除pdf：[{}]", pdfFiles.get(i).getLocalUrl());
				}
			}



		}
		resourceCoursewareService.delete(resourceCourseware);
		addMessage(redirectAttributes, "删除课件管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCourseware/?repage";
	}



  /*
   *批量删除
   */
	@RequiresPermissions("resource:resourceCourseware:edit")
	@RequestMapping(value = "deleteAdd")
	public String deleteAdd(String ids, RedirectAttributes redirectAttributes) {
		String[] id = ids.split(",");
		for (int p = 0; p < id.length; p++){
			ResourceCourseware resourceCourseware = new ResourceCourseware();
			resourceCourseware.setId(id[p]);
			ResourceFile material=new ResourceFile();
			material.setResourceId(resourceCourseware.getId());
			//删除素材表数据和ftp文件
			List<ResourceFile> materialList = resourceFileService.getMaterialsByCoursewareId(material);
			for(int i=0;i<materialList.size();i++)
			{
				resourceFileService.delete(materialList.get(i));  //数据库文件记录删除
				if(materialList.get(i).getLocalUrl()!=null&&!materialList.get(i).getLocalUrl().equals("")) {
					File file=new File(materialList.get(i).getLocalUrl());
					if(file.exists()) {
						file.delete();
						logger.debug("删除文件：[{}]", materialList.get(i).getLocalUrl());
					}
				}
				material.setType(ResourceConstants.image);
				material.setResourceId(materialList.get(i).getId());
				List<ResourceFile> pdfFiles= resourceFileService.findList(material);
				for(int j=0;j<pdfFiles.size();j++)
				{
					File file=new File(pdfFiles.get(j).getLocalUrl());
					if(file.exists()) {
						file.delete();
						logger.debug("删除pdf：[{}]", pdfFiles.get(i).getLocalUrl());
					}
				}
			}
			resourceCoursewareService.delete(resourceCourseware);
		}
		addMessage(redirectAttributes, "批量删除课件管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCourseware/?repage";
	}


//	/**
//	 * 上传文档素材文件
//	 *
//	 * @param file
//	 * @param response
//	 * @return
//	 */
//	@ResponseBody
//	@RequestMapping(value = "upload", method = RequestMethod.POST)
//	public String uploadFile(@RequestParam MultipartFile file, HttpServletResponse response) {
//		String OriginalFilename = file.getOriginalFilename();
//		String path = ResourceConstants.resourcePath;
//		Map<String, Object> result= fileUploadService.uploadFile(path,OriginalFilename, file);
//		boolean isSuccess=false;
//		if(result!=null)
//		{
//			isSuccess= (boolean) result.get("isSuccess");
//		}
//
//		if(isSuccess)
//		{
//			String ftpFileAddress= (String) result.get("ftpFileAddress");
//			ResourceFile resourceFile =new ResourceFile();
//			resourceFile.setFileName(OriginalFilename);
//			resourceFile.setFileType(ResourceConstants.documentMateria);// 素材类型：0：视频素材；1：文档素材
//			resourceFile.setFtpAddress(ftpFileAddress);
//			logger.debug("ftpFileAddress：[{}]", ftpFileAddress);
//
//			resourceFileService.save(resourceFile);
//			fileid= resourceFile.getId();
//		}
//
//		logger.debug("文件上传是否成功：[{}]",isSuccess);
//		logger.debug("fileid：[{}]", fileid);
//		if(fileid==null||fileid.equals(""))
//		{
//			fileid="";
//		}
//		try {
//			response.getWriter().write(fileid);  //ids换成后台获取到的文件id
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
	/**
	 * 上传文档素材文件
	 *
	 * @param file
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String uploadFile(@RequestParam MultipartFile file, HttpServletResponse response) {

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
		if(file!=null&&!file.isEmpty())
		{
			ResourceFile resourceFile=sysUploadUtils.saveFile(file,ResourceConstants.documentMateria);
			if(resourceFile!=null&&sysUploadUtils.isSuccess())
			{
				resourceFile.setType(ResourceConstants.documentMateria);// 素材类型：0：视频素材；1：文档素材
				resourceFileService.save(resourceFile);

				fileid= resourceFile.getId();

				logger.debug("文件上传是否成功：[{}]", sysUploadUtils.isSuccess());
				logger.debug("fileid：[{}]", fileid);
			}else {
				jsonModel.setSuccess(false);

			}
		}
		logger.debug("getMessage：[{}]", sysUploadUtils.getMessage());

		if(fileid==null||fileid.equals(""))
		{
			fileid="";
		}
		try {
			response.getWriter().write(fileid);  //ids换成后台获取到的文件id
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 上传视频素材文件
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "videoUpload", method = RequestMethod.POST)
	public JsonModel videoUpload(HttpServletRequest request, HttpServletResponse response) {

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
//		ResourceFile file=sysUploadUtils.uploadFile(request,ResourceConstants.videoMateria);

		ResourceFile resourceFile=null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					logger.debug("上传===");
					resourceFile=sysUploadUtils.saveFile(file,ResourceConstants.videoMateria);
				}
			}
		}
		logger.debug("上传视频素材文件成功===");
		logger.debug("上传==="+sysUploadUtils.getMessage());

		if(resourceFile!=null&&sysUploadUtils.isSuccess())
		{
			resourceFile.setType(ResourceConstants.videoMateria);// 素材类型：0：视频素材；1：文档素材
			resourceFileService.save(resourceFile);
			List<String> fileInfo=new ArrayList<>();
			fileInfo.add(resourceFile.getId());
			fileInfo.add(resourceFile.getUrl());
			jsonModel.setSuccess(true);
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setDataObj(fileInfo);
			return jsonModel;
		}else {
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setSuccess(false);
			return jsonModel;
		}
	}
	/**
	 * 上传课件文档
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "coursewareDocumentUpload", method = RequestMethod.POST)
	public JsonModel coursewareDocumentUpload(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("上传===coursewareDocumentUpload");

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
//		ResourceFile file=sysUploadUtils.uploadFile(request,ResourceConstants.videoMateria);

		ResourceFile resourceFile=null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					logger.debug("上传===");
					resourceFile=sysUploadUtils.saveFile(file,ResourceConstants.coursewareDocument);

				}
			}
		}
		logger.debug("上传课件文档成功===");
		logger.debug("上传==="+sysUploadUtils.getMessage());

		if(resourceFile!=null&&sysUploadUtils.isSuccess())
		{
			resourceFile.setType(ResourceConstants.coursewareDocument);// 0：课件文档
			resourceFileService.save(resourceFile);

			logger.debug("=Evan===resourceFile===: "+resourceFile);
			//线程删除网络内部类
			class PdfToImage extends Thread{
				private ResourceFile resourceFile;
				public PdfToImage(ResourceFile resourceFile) {
					this.resourceFile=resourceFile;
				}

				public void run() {
					logger.debug("dingh===pdf转image");
					//PDF to IMG
					File file = new File(resourceFile.getLocalUrl());
					//为了保存名称的唯一性，使用uuid
					String name = IdGen.uuid();
					//得到文件名
					String fileName = resourceFile.getName().substring(0, resourceFile.getName().lastIndexOf("."));
					//本地保存路径
					String fileLocalUrl = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + "resource" + "/" + name;
					//Url
					String fileUrl =  Global.USERFILES_BASE_URL + "resource" + "/" + name;

					try {
						PDDocument doc = PDDocument.load(file);
						PDFRenderer renderer = new PDFRenderer(doc);
						int pageCount = doc.getNumberOfPages();
						logger.debug("==Evan==pageCount: " + pageCount);

						for(int i=0;i<pageCount;i++){
							//rederImageWithDPI的第二个参数为dpi分辨率单位，可根据需求调节大小
							BufferedImage image = renderer.renderImageWithDPI(i, 196);
							//jar里另一种转图片的方法，第二个参数为缩放比
							//BufferedImage image = renderer.renderImage(i, 2.5f);
							ImageIO.write(image, "PNG", new File(fileLocalUrl + "(" + i + ")" + ".png"));

							//每转成一张图片，就往resource_file表里插入一条记录
							ResourceFile resourceFileImg = new ResourceFile();
							resourceFileImg.setResourceId(resourceFile.getId());
							resourceFileImg.setName(fileName+ "(" + i + ")" +".png");
							resourceFileImg.setType(ResourceConstants.image);
							resourceFileImg.setUrl(fileUrl + "(" + i + ")" +".png");
							resourceFileImg.setLocalUrl(fileLocalUrl + "(" + i + ")" +".png");
							resourceFileImg.setFormat("png");
							resourceFileService.save(resourceFileImg);

						}
						logger.debug("=Evan===PDF To IMG SUCCESS！===:");

					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			try{
				Thread t1 = new PdfToImage(resourceFile);
//		t1.start();
				t1.start();
				try {
					t1.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

//			ExecutorService pool= Executors.newCachedThreadPool();
////向线程池中提交线程
//			pool.submit(t1);
////关闭线程池
//			pool.shutdown();





			List<String> fileInfo=new ArrayList<>();
			fileInfo.add(resourceFile.getId());
			fileInfo.add(resourceFile.getUrl());
			jsonModel.setSuccess(true);
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setDataObj(fileInfo);
			return jsonModel;
		}else {
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setSuccess(false);
			return jsonModel;
		}
	}
	/**
	 * @param
	 * @return
	 * @author dingh
	 * @date 2017/2/25
	 * @des ajax展示已上传文档素材列表
	 */


	@ResponseBody
	@RequestMapping(value = "uploadFileList")
	public JsonModel uploadFileList(String[] ary) {
		logger.debug("ajax展示已上传文件列表:"+ary);
		List<ResourceFile> uploadFileList = new ArrayList<>();
		JsonModel jsonModel = new JsonModel();
		for (int i = 0; i < ary.length; i++) {
			ResourceFile file = resourceFileService.get(ary[i]);
			uploadFileList.add(file);
		}
		jsonModel.setDataObj(uploadFileList);
		jsonModel.setMsg("success");
		jsonModel.setSuccess(true);
		logger.debug("ajax展示已上传文件列表：[{}]",uploadFileList.size());

		return jsonModel;
	}
	/**
	 * @param
	 * @return
	 * @author dingh
	 * @date 2017/2/25
	 * @des ajax展示已上传视频素材列表
	 */


	@ResponseBody
	@RequestMapping(value = "videoFileList")
	public JsonModel videoFileList(String[] ary) {
		logger.debug("videoFile列表:"+ary);
		List<ResourceFile> uploadFileList = new ArrayList<>();
		JsonModel jsonModel = new JsonModel();
		for (int i = 0; i < ary.length; i++) {
			logger.debug("ary[i]:"+ary[i]);

			ResourceFile file = resourceFileService.get(ary[i]);
			uploadFileList.add(file);
		}
		jsonModel.setDataObj(uploadFileList);
		jsonModel.setMsg("success");
		jsonModel.setSuccess(true);
		logger.debug("ajax展示已上传文件列表：[{}]",uploadFileList.size());

		return jsonModel;
	}
	/**
	 * @param
	 * @return
	 * @author dingh
	 * @date 2017/2/25
	 * @des ajax删除已上传文件
	 */
	@ResponseBody
	@RequestMapping(value = "uploadFileDelete")
	public JsonModel uploadFileDelete(String uploadFileId) {
		JsonModel jsonModel = new JsonModel();
		logger.debug("uploadFileId:" + uploadFileId);

		ResourceFile deleteFile = resourceFileService.get(uploadFileId);
//		boolean message;
//		System.out.println("文件删除的路径===" + deleteFile.getUrl());
//		message = fileUploadService.deleteFile(deleteFile.getUrl()); //FTP文件删除
//		if (message) {
//			resourceFileService.delete(deleteFile);  //数据库文件记录删除
//			jsonModel.setSuccess(true);
//			String successMsg = "FTP文件删除成功。";
//			jsonModel.setMsg(successMsg);
//		} else {
//			jsonModel.setSuccess(false);
//			String failMsg = "FTP文件删除失败，请重试。";
//			jsonModel.setMsg(failMsg);
//		}
		resourceFileService.delete(deleteFile);  //数据库文件记录删除

		jsonModel.setSuccess(true);
		String successMsg = "文件删除成功。";
		jsonModel.setMsg(successMsg);
		jsonModel.setDataObj(uploadFileId);
		return jsonModel;
	}

	//查看课程学习情况
	@RequestMapping(value = "viewCourseLearnList")
	public String viewCourseLearnList(HttpServletRequest request, HttpServletResponse response, ResourceCourseware resourceCourseware, Model model, String courseId) {
		logger.debug("==Evan==viewCourseLearnList1=="+courseId);
		logger.debug("==Evan==viewCourseLearnList2=="+resourceCourseware.getCoursewareName());
		logger.debug("==Evan==viewCourseLearnList数据类型=="+courseId.subSequence(0,1));

		resourceCourseware.setCourseId((String) courseId.subSequence(0, 1) );
		Page<ResourceCourseware> page = resourceCoursewareService.viewCourseLearnList(new Page<ResourceCourseware>(request, response), resourceCourseware);
		model.addAttribute("page", page);
		return "modules/teach/teachViewCourseLearnList";
	}

	//进入课程学习-界面展示
	@RequestMapping(value = "findFileListByCoursewareId")
	public String findFileListByCoursewareId(String CoursewareId, String courseId, String classHour, Model model) {
		//根据课件id获取课件列表
		ResourceFile resourceFile = new ResourceFile();
		ResourceCourseware resourceCourseware=resourceCoursewareService.get(CoursewareId);
		resourceFile.setResourceId(CoursewareId);
		resourceFile.setType(ResourceConstants.videoMateria);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		//课件路径
		String filePath = null;
		if(fileList.size() != 0){
			filePath = fileList.get(0).getUrl();
		}
		//已完成课时
		int finishClassHour = 0;
		//为了界面刷新还能展示课件列表
		List<ResourceCourseware> CoursewareList = resourceCoursewareService.findListByCourseId(courseId);
		//获取所有课件的课件进度
		for(ResourceCourseware aCoursewareList: CoursewareList){
			//累计已完成课时
			if(teachStudentService.findTeachStudentCourseware(aCoursewareList.getId()).getLearnProgress() == LearnProgress.finish) {
				finishClassHour++;
			}
			aCoursewareList.setLearnProgress(teachStudentService.findTeachStudentCourseware(aCoursewareList.getId()).getLearnProgress() );
		}
		//根据课件Id获取单条课件记录
		ResourceCourseware Courseware = resourceCoursewareService.get(CoursewareId);
		model.addAttribute("CoursewareList", CoursewareList);
		model.addAttribute("filePath", filePath);
		model.addAttribute("CoursewareId",CoursewareId);
		model.addAttribute("CoursewareName",Courseware.getCoursewareName());
		model.addAttribute("resourceCourseware",resourceCourseware);
		model.addAttribute("courseId",courseId);
		model.addAttribute("classHour", classHour);
		model.addAttribute("finishClassHour", finishClassHour);
		return "modules/teach/stuCourseLearn";
	}

	//进入课程学习-判断课件是否包含视频文件
	@ResponseBody
	@RequestMapping(value = "checkHasVideoFile")
	public String checkHasVideoFile(String CoursewareId) {
		logger.debug("==Evan==checkHasVideoFile=="+CoursewareId);
		//根据课件id获取课件列表
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(CoursewareId);
		resourceFile.setType(ResourceConstants.videoMateria);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		logger.debug("==Evan==fileList.size()=="+fileList.size());
		//课件路径
		String filePath = null;
		if(fileList.size() != 0){
			filePath = fileList.get(0).getUrl();
		}
		return filePath;
	}

	//进入课程学习-下载课程文档   调用浏览器各自的下载方式
	@RequestMapping(value = "downloadDocFiles")
	public String downloadDocFiles(String courseId, HttpServletResponse response) throws IOException, URISyntaxException {
		List<ResourceCourseware> CoursewareList = resourceCoursewareService.findListByCourseId(courseId);
		ArrayList<ResourceFile> totalFileList = new ArrayList<>();
		//循环该课程下所有课件
		for (ResourceCourseware aCoursewareList : CoursewareList) {
			logger.debug("==Evan==CoursewareList" + aCoursewareList);
			ResourceFile resourceFile = new ResourceFile();
			resourceFile.setResourceId(aCoursewareList.getId());
			resourceFile.setType(ResourceConstants.coursewareDocument);   //'5': 课件文档
			List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
			//循环所有课件下的所有文档
			for (ResourceFile aFileList : fileList) {
				logger.debug("==Evan==aFileList" + aFileList);
				totalFileList.add(aFileList);
			}
		}
		logger.debug("==Evan111111==totalFileNum: " + totalFileList.size() + "  totalFileList: " + totalFileList);

		response.setCharacterEncoding("utf-8");
		response.setContentType("APPLICATION/OCTET-STREAM");
		//设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode( "课程文档" + sdf.format(new Date()) + ".zip", "UTF-8"));
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(resourceCourseService.get(courseId).getCourseName() + "_课程文档" + ".zip", "UTF-8"));
		//创建输出流
		OutputStream os = response.getOutputStream();
		byte[] buf = new byte[1024];
		try {
			//ZipOutputStream类：完成文件或文件夹的压缩
			ZipOutputStream out = new ZipOutputStream(os);
			for (ResourceFile aTotalFileList : totalFileList) {
				FileInputStream fis = new FileInputStream(aTotalFileList.getLocalUrl());
				out.putNextEntry(new ZipEntry(aTotalFileList.getName()));
				int len;
				while ((len = fis.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				fis.close();
			}
			out.flush();
			out.close();
			logger.debug("Evan========压缩完成!!!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	//进入课程学习-点击查看文档-获取图片列表
	@ResponseBody
	@RequestMapping(value = "getImgList")
	public List<ResourceFile> getImgList(String CoursewareId) {
		logger.debug("==Evan==getImgList=="+CoursewareId);
		//根据课件id获取课件列表
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(CoursewareId);
		resourceFile.setType(ResourceConstants.image);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		logger.debug("==Evan==fileList.size()=="+fileList.size());
		logger.debug("==Evan==fileList=="+fileList);
		return fileList;
	}


	@ResponseBody
	@RequestMapping(value = "Base64Upload")
	public Map Base64Upload(@RequestParam(value = "strBase64", required = true) String strBase64) {
		return base64ImageService1.base64ToImg(strBase64);
	}

	@RequestMapping(value = "upload1")
	public String upload1(Model model) {

		return "modules/resource/upload1";
	}
	@RequestMapping("uploadFileProgress")
	public void uploadFileProgress(HttpServletRequest request,HttpServletResponse response,
						   @RequestParam("file") MultipartFile file) throws IOException {
		logger.debug("==Evan==uploadFileProgress==");

		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		PrintWriter out;
		boolean flag = false;
		if (file.getSize() > 0) {
			//文件上传的位置可以自定义
			logger.debug("==Evan==uploadFileProgress=="+file.getOriginalFilename());

			try {
				Thread.sleep(3000);
				flag=true;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		out = response.getWriter();
		if (flag == true) {
			out.print("1");
		} else {
			out.print("2");
		}
	}
}